package com.drinks.yiniang.io.http;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * 继承RequestBody,实现okhttp3上传的进度监听
 * Created by han on 2017/5/23 0023.
 */
public class ProgressRequestBody extends RequestBody {

    MediaType contentType;
    File file;
    ProgressListener listener;
    int id;

    /**
     * 构造函数
     *
     * @param id          一次可以上传多个文件,id表示本文件在这一批文件当中的编号
     * @param contentType MIME类型
     * @param file        要上传的文件
     * @param listener    传输进度监听器
     */
    public ProgressRequestBody(int id, MediaType contentType, File file, ProgressListener listener) {
        this.id = id;
        this.contentType = contentType;
        this.file = file;
        this.listener = listener;
    }

    @Override
    public MediaType contentType() {
        return contentType;
    }

    @Override
    public long contentLength() throws IOException {
        return file.length();
    }


    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        long len;//记录本次读了多少数据
        long currSize = 0;//记录目前一共读了多少数据
        long totalSize = contentLength();//一共有多少数据

        try {
            source = Okio.source(file);
            Buffer buffer = new Buffer();

            while ((len = source.read(buffer, 2048)) != -1) {
                sink.write(buffer, len);
                sink.flush();
                currSize += len;

                //回调,进度监听
                listener.onProgress(totalSize, currSize, totalSize == currSize, id);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (source != null) {
                    source.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getFilename() {
        return file != null ? file.getName() : "file";
    }

    /**
     * 传输进度监听器
     */

    public interface ProgressListener {
        /**
         *
         * @param totalSize 总大小
         * @param currSize 当前大小
         * @param done 是否完成
         * @param id 序号
         */
        void onProgress(long totalSize, long currSize, boolean done, int id);
    }
}
